//
//  TCAirportViewController.m
//  EFBTerminalCharts
//
//  Created by xiu-imac on 13-10-29.
//  Copyright (c) 2013年 adcc. All rights reserved.
//

#import "TCAirportViewController.h"
#import "TCAirportModel.h"
#import "TCAirportCell.h"
#import "ChartContext.h"


@interface TCAirportViewController () <UITabBarDelegate>
{
	bool isTaskAirport;
	NSString *selectedICAO;
}

@property (retain, nonatomic) IBOutlet UITableView *airportTableView;
@property (retain, nonatomic) IBOutlet UISearchBar *airportSearchBar;
@property (retain, nonatomic) NSMutableArray *filterAirportArray;
@property (retain, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (retain, nonatomic) IBOutlet UITabBar *tabBar;

@property (retain, nonatomic) NSMutableArray *airportDataArray;

@end

@implementation TCAirportViewController

- (void)dealloc {
    [_airportDataArray release];
	[_airportTableView release];
	[_airportSearchBar release];
    [_filterAirportArray release];
    [_navigationBar release];
    [_tabBar release];
	[super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	isTaskAirport = false;
    self.view.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    self.airportDataArray = [[[NSMutableArray alloc] init] autorelease];
    
    _tabBar.translucent = NO;
    _tabBar.tintColor = [UIColor colorWithRed:185/255.0 green:235/255.0 blue:255/255.0 alpha:1.0];
    _tabBar.barTintColor = [UIColor colorWithRed:48/255.0 green:62/255.0 blue:75/255.0 alpha:1.0];
    [_tabBar setSelectedItem:[_tabBar.items firstObject]];
    
    UITabBarItem *item = [_tabBar.items firstObject];
    UITabBarItem *item1 = [_tabBar.items lastObject];

    item.title = NSLocalizedString(@"all-airports", @"所有机场");
    item1.title = NSLocalizedString(@"task-airports", @"任务机场");

    [_navigationBar setBarTintColor:[UIColor colorWithRed:48/255.0 green:62/255.0 blue:75/255.0 alpha:1.0]];
    _navigationBar.topItem.title = NSLocalizedString(@"all-airports", @"所有机场");
    _navigationBar.translucent = NO;
    
	_airportTableView.delegate = self;
	_airportTableView.dataSource = self;
	_airportTableView.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _airportTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	_airportSearchBar.autocapitalizationType=UITextAutocapitalizationTypeAllCharacters;
    _airportSearchBar.placeholder=NSLocalizedString(@"search-for-airports", @"查找机场");
    _airportSearchBar.delegate= self;
	[_airportSearchBar setBarStyle:UIBarStyleDefault];
    _airportSearchBar.tintColor=[UIColor blueColor];

    UIView *searchBarView = [[self.airportSearchBar subviews] lastObject];
    for (UITextField *searchField in searchBarView.subviews) {
        if ([searchField isKindOfClass: NSClassFromString ( @"UISearchBarTextField" )]) {
            searchField.backgroundColor = [UIColor whiteColor];
            searchField.textColor = [UIColor blackColor];
            break ;
        }
    }
    for (UIView *view in searchBarView.subviews) {
        if ([view isKindOfClass: NSClassFromString ( @"UISearchBarBackground" )]) {
            [view removeFromSuperview];
            self.airportSearchBar.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0f];
            break ;
        }
    }
}

#pragma mark --NSNotification--- 显示当前关联的飞行任务
-(void)showFlightTaskAlert:(NSNotification *)notification
{
    if (isTaskAirport)
	{
		[self.airportTableView reloadData];
	}
}

#pragma mark tableview datasource method

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

	if (isTaskAirport)
	{
        NSInteger count = [[TCAirportModel getTaskAirportArray] count];
        if (count == 0) {
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
		return count;
        
	}
    else
	{
		if ([_airportSearchBar.text isEqualToString:@""])
		{
//			return [[TCAirportModel getAirportArray] count];
            return [self.airportDataArray count];
		}
		else
		{
			return [_filterAirportArray count];
		}
	}
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *airportsIdentifier=@"airportsIdentifier";
	TCAirportCell *cell=[[[TCAirportCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:airportsIdentifier ] autorelease];;
    
    if (cell==nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TCAirportCell" owner:self options:nil]objectAtIndex:0];
	}
	if (isTaskAirport) {
		[cell.icaoLabel setText:[[[TCAirportModel getTaskAirportArray] objectAtIndex:indexPath.row] objectForKey:@"icao"]];
		[cell.nameLabel setText:[[[TCAirportModel getTaskAirportArray] objectAtIndex:indexPath.row] objectForKey:@"name"]];
	}
	else
	{
		if([_airportSearchBar.text isEqualToString:@""])
		{
            [cell.icaoLabel setText:[[self.airportDataArray objectAtIndex:indexPath.row] objectForKey:@"icao"]];
            [cell.nameLabel setText:[[self.airportDataArray objectAtIndex:indexPath.row] objectForKey:@"name"]];
		}
		else
		{
			[cell.icaoLabel setText:[[_filterAirportArray objectAtIndex:indexPath.row] objectForKey:@"icao"]];
			[cell.nameLabel setText:[[_filterAirportArray objectAtIndex:indexPath.row] objectForKey:@"name"]];
		}
	}
    
    if ([cell.icaoLabel.text isEqualToString:[TCAirportModel getAirportICAO]]) {
        selectedICAO = cell.icaoLabel.text;
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *icao = nil;
	if (isTaskAirport)
	{
		icao = [[[TCAirportModel getTaskAirportArray] objectAtIndex:[indexPath row]] objectForKey:@"icao"];
	}
	else
	{
		if ([_airportSearchBar.text isEqualToString:@""])
		{
            icao = [[self.airportDataArray objectAtIndex:[indexPath row]] objectForKey:@"icao"];
		}
		else
		{
			icao = [[_filterAirportArray objectAtIndex:[indexPath row]] objectForKey:@"icao"];
		}
	}
	
	if (selectedICAO != nil && [selectedICAO isEqualToString:icao]) {
		return;
	}
	selectedICAO = icao;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"selectedAirportOfChartsChanged" object:selectedICAO];
    [[NSUserDefaults standardUserDefaults] setValue:selectedICAO forKey:@"blueSiZiMa"];
}


#pragma ---

#pragma mark button event

- (void)chartTableViewReload:(NSNotification *)notification
{
    [_airportTableView reloadData];
}

#pragma mark - UISearchBar Delegate Method

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	[self getFilterAirportArray:searchText];
    [_airportTableView reloadData];
}

-(void)getFilterAirportArray:(NSString *)filter
{
	NSMutableArray *filterArray = [[[NSMutableArray alloc]init]autorelease];
    NSArray *dataArray = [NSArray arrayWithArray:[TCAirportModel getAirportArray]];
	for (NSDictionary *dic in dataArray) {
		NSRange r = [[dic objectForKey:@"icao"] rangeOfString:filter options:NSCaseInsensitiveSearch];
		if (r.location != NSNotFound) {
			[filterArray addObject:dic];
		}
	}
	self.filterAirportArray = filterArray;
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    switch (item.tag) {
        case 0:{
            if(isTaskAirport)
            {
                isTaskAirport = false;
                [_airportSearchBar setHidden:NO];
                [_airportTableView setFrame:CGRectMake(0, 88, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-143)];
                _navigationBar.topItem.title = NSLocalizedString(@"all-airports", @"所有机场");
                item.title = NSLocalizedString(@"all-airports", @"所有机场");
                [_airportTableView reloadData];
            }
            break;
        }
        case 1:{
            if(!isTaskAirport)
            {
                isTaskAirport = true;
                [_airportTableView setFrame:CGRectMake(0, 44, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-99)];
                [_airportSearchBar setHidden:YES];
                _navigationBar.topItem.title = NSLocalizedString(@"task-airports", @"任务机场");
                item.title = NSLocalizedString(@"task-airports", @"任务机场");
                [_airportTableView reloadData];
            }
            break;
        }
        default:
            break;
    }
}

#pragma ---

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(isTaskAirport)
	{
		[_airportTableView setFrame:CGRectMake(0, 44, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-99)];
		[_airportSearchBar setHidden:YES];
    }
    
//    if (![selectedICAO isEqualToString:[TCAirportModel getAirportICAO]]) {
        self.airportDataArray = [NSMutableArray arrayWithArray:[TCAirportModel getAirportArray]];
        [_airportTableView reloadData];
//    }
}

@end
